package com.zhuqi.netty.handler;

import com.zhuqi.netty.bootstrap.ChatClient;
import com.zhuqi.param.ConstParam;
import com.zhuqi.netty.properties.NettyClientProperties;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * <p>类描述</p>
 * @author zhuqi
 * @since 2023/3/10 14:23
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class BasicHandler extends ChannelInboundHandlerAdapter {


	@Autowired
	private NettyClientProperties nettyClientProperties;

	/**
	 * 链接建立后触发 active 事件
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		// 赋值 ctx
		ChatClient.ctx = ctx;
	}

	/**
	 * 连接断开
	 */
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// 判断是否为正常退出
		if (ChatClient.exit.get()) {
			log.info("连接断开，关闭线程池");
			ChatClient.shutdown();
			return;
		}
		for (int i = 0; i < ConstParam.reConnectCount; i++) {
			doReConnect(i);
			// 登陆 加锁60
			TimeUnit.SECONDS.sleep(60L);
			if (!ChatClient.exit.get()) {
				log.info("重连成功");
				return;
			}
		}
		log.info("关闭客户端");
		ChatClient.shutdown();
	}

	/**
	 * 重连
	 * @param count 重连次数
	 */
	private void doReConnect(int count) {
		log.info("连接断开，正在重新连接" + "-" + count);
		ChatClient.bootstrap.connect(nettyClientProperties.getIp(), nettyClientProperties.getPort())
				.addListener((ChannelFutureListener) future -> {
					if (future.isSuccess()) {
						log.info("重新连接成功");
						ChatClient.exit.set(false);
						// TODO: 2023/4/19 需要用户重新登陆

					}
				});
	}


}
